import { getUserInfo, login, getUserInfoById } from '@/api/user'
import {
  getToken,
  setToken,
  removeToken,
  setTimeStamp } from '@/utils/auth'

const state = {
  token: getToken(),
  userInfo: {}
}

const mutations = {
  setToken(state, data) {
    state.token = data
    setToken(data)
  },
  removeToken(state) {
    state.token = ''
    removeToken()
  },
  setUserInfo(state, data) {
    state.userInfo = { ...data } // ‘...’可以切割...data与data之间的联系，使得state.userInfo的值不会因为data的变化而改变自己
  },
  removeUserInfo(state, data) {
    state.userInfo = {}
  }
}

const actions = {
  async login(store, data) {
    try {
      const res = await login(data)
      console.log(res)
      store.commit('setToken', res)
      setTimeStamp()
    } catch (error) {
      console.log('failed')
    }
  },
  async getUserInfo(store) {
    const res = await getUserInfo()
    const userDetail = await getUserInfoById(res.userId)
    const data = {
      ...res,
      ...userDetail
    }
    store.commit('setUserInfo', data)
  },
  logout(store) {
    store.commit('removeToken')
    store.commit('removeUserInfo')
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

